package com.qunar.wan.web.controller.common;

import com.qunar.wan.common_api.exception.UnauthenticatedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Map;

/**
 * User: C.young Date: 11/25/13 Time:11:27 AM
 */
@Controller
public class ExceptionJsonController {
    protected Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 对异常进行自动捕获处理，具体可以根据异常以及自定义异常进行细分
     * 
     * @param ex
     * @return Json
     */
    @ExceptionHandler(RuntimeException.class)
    public @ResponseBody
    DataMap baseExceptionHandler(RuntimeException ex) {
        logger.error("", ex);

        DataMap map = new DataMap();
        map.put("ret", false);
        if (ex instanceof IllegalArgumentException) {
            map.put("errcode", HttpStatus.BAD_REQUEST);
            map.put("errmsg", "参数不合法");
        } else if (ex instanceof NullPointerException) {
            map.put("errcode", "NEP");
            map.put("errmsg", "包含为Null的数据");

        } else if (ex instanceof UnauthenticatedException) {
            map.put("errcode", HttpStatus.FORBIDDEN);
            map.put("errmsg", "权限不足");

        } else {
            map.put("errcode", HttpStatus.INTERNAL_SERVER_ERROR);
            map.put("errmsg", "系统内部出错");
        }
        return map;
    }

    @RequestMapping(value = "/unauthen")
    @ResponseBody
    public Object unauthenException() {
        Map map = new ModelMap();
        map.put("ret", false);
        map.put("errcode", HttpStatus.FORBIDDEN);
        map.put("errmsg", "未登录或者权限不够");
        return map;
    }

}
